package com.zyj.test.month1.day15;

/**
 * @author Yijia Zhang
 * @create 2024-06-04 21:05
 */
public class code0028 {
    public int strStr(String haystack, String needle) {
        int[] next = nextArr(needle);
        int j = 0;
        for (int i = 0; i < haystack.length(); i++) {
            while (j > 0 && haystack.charAt(i) != needle.charAt(j)) {
                j = next[j - 1];
            }
            if (haystack.charAt(i) == needle.charAt(j)) {
                j++;
            }
            if (j == next.length) {
                return i - j + 1;
            }
        }
        return -1;
    }

    public int[] nextArr(String s) {
        char[] cs = s.toCharArray();
        int len = s.length();
        int[] res = new int[len];
        for (int j = 0, i = 1; i < len; i++) {
            while (j > 0 && cs[i] != cs[j]) {
                j = res[j - 1];
            }
            if (cs[i] == cs[j]) {
                j++;
            }
            res[i] = j;
        }
        return res;
     }
}
